//! 服务端API接口模块
//!
//! 该模块提供RESTful API和gRPC API接口

pub mod rest;
pub mod grpc;
pub mod handler;
pub mod middleware;
pub mod server;

pub use rest::*;
pub use grpc::*;
pub use handler::*;
pub use middleware::*;
pub use server::*;

use std::sync::Arc;
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};

/// 服务器错误类型
#[derive(Debug, thiserror::Error)]
pub enum ServerError {
    #[error("网络错误: {0}")]
    Network(String),
    
    #[error("配置错误: {0}")]
    Config(String),
    
    #[error("集群错误: {0}")]
    Cluster(String),
    
    #[error("存储错误: {0}")]
    Storage(String),
    
    #[error("认证错误: {0}")]
    Auth(String),
    
    #[error("限流错误: {0}")]
    RateLimit(String),
    
    #[error("内部错误: {0}")]
    Internal(String),
}

/// API响应统一格式
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    pub code: i32,
    pub message: String,
    pub data: Option<T>,
    pub timestamp: i64,
}

impl<T> ApiResponse<T> {
    pub fn success(data: T) -> Self {
        Self {
            code: 200,
            message: "success".to_string(),
            data: Some(data),
            timestamp: chrono::Utc::now().timestamp(),
        }
    }

    pub fn error(message: String) -> Self {
        Self {
            code: 500,
            message,
            data: None,
            timestamp: chrono::Utc::now().timestamp(),
        }
    }

    pub fn not_found(message: String) -> Self {
        Self {
            code: 404,
            message,
            data: None,
            timestamp: chrono::Utc::now().timestamp(),
        }
    }
}

/// API配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiConfig {
    pub rest_port: u16,
    pub grpc_port: u16,
    pub cors_enabled: bool,
    pub rate_limit_enabled: bool,
    pub max_connections: usize,
    pub request_timeout: u64,
}

impl Default for ApiConfig {
    fn default() -> Self {
        Self {
            rest_port: 8848,
            grpc_port: 9090,
            cors_enabled: true,
            rate_limit_enabled: true,
            max_connections: 1000,
            request_timeout: 5000,
        }
    }
}

/// API路由管理器
pub struct ApiRouter {
    routes: Arc<RwLock<Vec<Route>>>,
    middlewares: Arc<RwLock<Vec<Middleware>>>,
}

pub struct Route {
    pub path: String,
    pub method: String,
    pub handler: Box<dyn RequestHandler>,
}

#[async_trait::async_trait]
pub trait RequestHandler: Send + Sync {
    async fn handle(&self, request: Request) -> Result<Response, Box<dyn std::error::Error + Send + Sync>>;
}

/// 中间件枚举类型，用于解决dyn兼容性问题
#[derive(Debug, Clone)]
pub enum Middleware {
    Cors(CorsMiddleware),
    RateLimit(RateLimitMiddleware),
    Auth(AuthMiddleware),
    Logging(LoggingMiddleware),
    RequestId(RequestIdMiddleware),
    Timeout(TimeoutMiddleware),
}

#[async_trait::async_trait]
pub trait MiddlewareTrait: Send + Sync {
    async fn process(
        &self, 
        request: Request
    ) -> Result<Request, Box<dyn std::error::Error + Send + Sync>>;
}

impl Middleware {
    pub async fn process(
        &self,
        request: Request
    ) -> Result<Request, Box<dyn std::error::Error + Send + Sync>> {
        match self {
            Middleware::Cors(m) => m.process(request).await,
            Middleware::RateLimit(m) => m.process(request).await,
            Middleware::Auth(m) => m.process(request).await,
            Middleware::Logging(m) => m.process(request).await,
            Middleware::RequestId(m) => m.process(request).await,
            Middleware::Timeout(m) => m.process(request).await,
        }
    }
}

/// HTTP请求
#[derive(Debug, Clone)]
pub struct Request {
    pub method: String,
    pub path: String,
    pub headers: std::collections::HashMap<String, String>,
    pub query_params: std::collections::HashMap<String, String>,
    pub body: Vec<u8>,
    pub remote_addr: String,
}

/// HTTP响应
#[derive(Debug, Clone)]
pub struct Response {
    pub status_code: u16,
    pub headers: std::collections::HashMap<String, String>,
    pub body: Vec<u8>,
}

impl ApiRouter {
    pub fn new() -> Self {
        Self {
            routes: Arc::new(RwLock::new(Vec::new())),
            middlewares: Arc::new(RwLock::new(Vec::new())),
        }
    }

    pub async fn add_route(&self, route: Route) {
        let mut routes = self.routes.write().await;
        routes.push(route);
    }

    pub async fn add_middleware(&self, middleware: Middleware) {
        let mut middlewares = self.middlewares.write().await;
        middlewares.push(middleware);
    }

    pub async fn route(&self, request: Request) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
        // 应用中间件
        let mut request = request;
        let middlewares = self.middlewares.read().await;
        for middleware in middlewares.iter() {
            request = middleware.process(request).await?;
        }

        // 查找路由
        let routes = self.routes.read().await;
        for route in routes.iter() {
            if route.method == request.method && route.path == request.path {
                return route.handler.handle(request).await;
            }
        }

        Ok(Response {
            status_code: 404,
            headers: std::collections::HashMap::new(),
            body: b"Not Found".to_vec(),
        })
    }
}